package com.heima.admin.controller.v1;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.SensitiveDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/api/v1/sensitive")
public class WmSensitiveController {

    @Autowired
    private IWemediaClient wemediaClient;

    @PostMapping("/list")
    @ResponseBody
    public PageResponseResult list(@RequestBody SensitiveDto dto) {
        return wemediaClient.findSensitiveList(dto);
    }

    @PostMapping("/save")
    @ResponseBody
    public ResponseResult insert(@RequestBody WmSensitive wmSensitive) {
        return wemediaClient.insertSensitive(wmSensitive);
    }

    @PostMapping("/update")
    @ResponseBody
    public ResponseResult update(@RequestBody WmSensitive wmSensitive) {
        return wemediaClient.updateSensitive(wmSensitive);
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public ResponseResult delete(@PathVariable("id") Integer id) {
        return wemediaClient.deleteSensitive(id);
    }

    @RequestMapping("/download")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        File file = new File("D:\\workspace\\template.xlsx");
        if (file.exists()) {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("敏感词库模板.xlsx", "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                assert bis != null;
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @PostMapping("/upload")
    @ResponseBody
    public ResponseResult upload(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //如果后缀不是xlsx || xls则不能解析文件
        if (checkParam(postfix)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文件格式不正确");
        }

        List<WmSensitive> wmSensitiveList = null;
        try {
            ImportParams importParams = new ImportParams();
            importParams.setHeadRows(1);
            importParams.setSheetNum(1);
            //excle文件导入
            wmSensitiveList = ExcelImportUtil.importExcel(multipartFile.getInputStream(), WmSensitive.class, importParams);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.EXCEL_REPORT_FAIL);
        }
        //批量导入
        wemediaClient.importSensitive(wmSensitiveList);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private boolean checkParam(String postfix){
        if(postfix.equals("xlsx") || postfix.equals("xls")){
            return false;
        }
        return true;
    }
}
